<!-- 交易页面：秒合约，币币交易，U本位 -->
<template>
  <div>
    <!-- tabs -->
    <van-sticky>
      <div class="headerList">
        <div class="left">
          <svg-load name="jiantou-z" class="leftImg" @click="_back()"></svg-load>
        </div>
        <div class="headerChoose">
          <van-tabs
            swipeable
            shrink
            :swipe-threshold="2"
            v-model:active="currentIndex"
            line-width="20"
            line-height="2"
            color="#17ac74"
            title-active-color="#17AC74"
            title-inactive-color="#5d626d"
          >
            <van-tab v-for="(item, index) in headerList" :key="index" :title="item.title">
            </van-tab>
          </van-tabs>
        </div>
      </div>
    </van-sticky>
    <!-- tab -->
    <component
        :is="currentComponent"
        :headerList="headerList"
    ></component>
  </div>
</template>

<script setup>
import { _t18 } from '@/utils/public'
import { useMainStore } from '@/store/index'
import { useTradeStore } from '@/store/trade'
import { useRoute } from 'vue-router'
import { computed, onMounted, onUnmounted, watch } from 'vue'
import SecondContract from './components/tradeSecondContract.vue'
import BBTrading from './components/tradeBBTrading.vue'
import Ustandard from './components/tradeUstandard.vue'
import Guaranteed from './components/tradeGuaranteed.vue'
import {getMt5Amount, showOrdecoinInfo} from "@/api/trade"
import spontaneousCoinService from '@/utils/spontaneousCoinPolling'
import { getSpontaneousCoinPricesApi } from '@/api/spontaneous'

const mainStore = useMainStore()
const tradeStore = useTradeStore()
const $route = useRoute()

// tabs
const headerList = computed(() => {
  let tempList = mainStore.getTradeHeaderList.filter((item, index) => {
    return item.componentName != 'Optional'
  })
  return tempList
})

const currentIndex = ref(
  mainStore.tradeFlag - mainStore.isOption < 0 ? 0 : mainStore.tradeFlag - mainStore.isOption
)

// 切换组件
const currentComponent = computed(() => {
  let temp = ''
  if (headerList.value[currentIndex.value].componentName == 'SecondContract') {
    temp = SecondContract
  }else if (headerList.value[currentIndex.value].componentName == 'BBTrading') {
    temp = BBTrading
  }else if (headerList.value[currentIndex.value].componentName == 'Ustandard') {
    temp = Ustandard
  }else if (headerList.value[currentIndex.value].componentName == 'Guaranteed') {
    temp = Guaranteed
  }
  return temp
})

/**
 * 检查是否为币
 * @param {Object} coin 币种信息
 * @returns {boolean}
 */
const isSpontaneousCoin = (coin) => {
  if (!coin) {
    return false
  }
  
  // 多种判断条件，确保准确识别币
  const isSpontaneous = (
    coin.market === 'spontaneous' || 
    coin.spontaneousCoin === true ||
    coin.spontaneousCoin === 1 ||
    coin.spontaneousCoin === '1' ||
    coin.coinType === 'spontaneous' ||
    coin.type === 'spontaneous'
  )
  
  console.log(`币种 ${coin.coin} 币判断:`, {
    market: coin.market,
    spontaneousCoin: coin.spontaneousCoin,
    coinType: coin.coinType,
    type: coin.type,
    isSpontaneous
  })
  
  return isSpontaneous
}

/**
 * 获取所有币种列表
 * @returns {Array} 币种列表
 */
const getSpontaneousCoins = () => {
  const spontaneousCoins = []
  
  // 检查币币交易列表
  tradeStore.spotCoinList.forEach(coin => {
    if (isSpontaneousCoin(coin)) {
      spontaneousCoins.push(coin.coin)
    }
  })
  
  // 检查秒合约列表
  tradeStore.secondContractCoinList.forEach(coin => {
    if (isSpontaneousCoin(coin)) {
      spontaneousCoins.push(coin.coin)
    }
  })
  
  // 检查U本位列表
  tradeStore.contractCoinList.forEach(coin => {
    if (isSpontaneousCoin(coin)) {
      spontaneousCoins.push(coin.coin)
    }
  })
  
  return [...new Set(spontaneousCoins)] // 去重
}

/**
 * 币种价格更新回调
 * @param {Object} priceData 价格数据
 */
const onSpontaneousCoinPriceUpdate = (priceData) => {

  // 更新tradeStore中的价格信息
  if (priceData && priceData.symbol) {
    const currentPriceInfo = tradeStore.allCoinPriceInfo[priceData.symbol] || {}
    
    // 更新价格信息
    const updatedPriceInfo = {
      ...currentPriceInfo,
      close: priceData.close || priceData.price || currentPriceInfo.close,
      high24: priceData.high || priceData.high24 || currentPriceInfo.high24,
      low24: priceData.low || priceData.low24 || currentPriceInfo.low24,
      volume24: priceData.volume || priceData.volume24 || currentPriceInfo.volume24,
      priceChangePercent: priceData.changePercent || priceData.priceChangePercent || currentPriceInfo.priceChangePercent,
      openPrice: priceData.open || priceData.openPrice || currentPriceInfo.openPrice
    }
    
    // 更新store
    tradeStore.updateCoinPriceInfo(priceData.symbol, updatedPriceInfo)
    
  }
}

/**
 * 获取所有币价格（单次请求）
 */
const getAllSpontaneousCoinPrices = async () => {
  try {
    const spontaneousCoins = getSpontaneousCoins()
    console.log('发现的币:', spontaneousCoins)
    
    if (spontaneousCoins.length === 0) {
      console.log('未发现币，跳过价格获取')
      return
    }
    
    // 批量获取所有币价格
    console.log(`开始获取 ${spontaneousCoins.length} 个币的价格`)
    await spontaneousCoinService.getMultipleSpontaneousCoinPrices(spontaneousCoins, onSpontaneousCoinPriceUpdate)
    
    console.log(`成功获取 ${spontaneousCoins.length} 个币的价格`)
  } catch (error) {
    console.error('获取币价格失败:', error)
  }
}

/**
 * 清除所有请求状态
 */
const clearAllRequestStatus = () => {
  spontaneousCoinService.clearAllRequestStatus()
}

watch(
  currentIndex,
  (n) => {
    mainStore.setTradeFlag(n)
    // tradeStore.getCoinList()
    /* if (headerList.value[n].componentName == 'SecondContract') {
      let temp={}
      if ($route.query.symbol) {
        temp = tradeStore.secondContractCoinList.filter((item, index) => {
          return item.coin === $route.query.symbol
        })[0]
        if (!temp) {
          temp = tradeStore.secondContractCoinList[0]
        }
      } else {
        temp = tradeStore.secondContractCoinList[0]
      }
      coinInfo2.value=temp
    } else if (headerList.value[currentIndex.value].componentName == 'BBTrading') {
      let temp={}
      if ($route.query.symbol) {
        temp = tradeStore.spotCoinList.filter((item, index) => {
          return item.coin === $route.query.symbol
        })[0]
        if (!temp) {
          temp = tradeStore.spotCoinList[0]
        }
      } else {
        temp = tradeStore.spotCoinList[0]
      }
      coinInfo2.value=temp
    } else if (headerList.value[currentIndex.value].componentName == 'Ustandard') {
      let temp={}
      if ($route.query.symbol) {
        temp = tradeStore.contractCoinList.filter((item, index) => {
          return item.coin === $route.query.symbol
        })[0]
        if (!temp) {
          temp = tradeStore.contractCoinList[0]
        }
      } else {
        temp = tradeStore.contractCoinList[0]
      }
      coinInfo2.value=temp
    } */
  },
  { immediate: true }
)

onMounted(async (option) => {
  console.log('页面加载开始，query:', $route.query)
  
  try {
    // 1. 先获取币种列表
    console.log('开始获取币种列表...')
    await tradeStore.getCoinList()
    console.log('币种列表获取完成')
    
    // 2. 获取币种信息
    if ($route.query.symbol) {
      console.log('获取币种信息:', $route.query.symbol)
      await showOrdecoinInfo($route.query.symbol, 'KEEP')
    }
    
    // 3. 获取币价格（只对币发起请求）
    console.log('开始获取币价格...')
    await getAllSpontaneousCoinPrices()
    console.log('币价格获取完成')
    
  } catch (error) {
    console.error('页面初始化失败:', error)
    // 即使出错也要尝试获取价格
    getAllSpontaneousCoinPrices()
  }
})

onUnmounted(() => {
  // 清除所有请求状态
  clearAllRequestStatus()
})
</script>

<style lang="scss" scoped>
.headerList {
  height: 60px;
  border-bottom: 1px solid var(--ex-border-color);
  display: flex;
  align-items: center;
  background: var(--ex-home-list-bgcolor);
  z-index: 9;
  padding-left: 15px;

  .left {
    display: flex;
    font-size: 16px;
    font-weight: normal;
    color: var(--ex-default-font-color);

    .leftImg {
      width: 16px;
      height: 12px;
      margin-right: 15px;
    }
  }

  .headerChoose {
    display: flex;
    padding: 0 15px 0 0;
    background: var(--ex-home-list-bgcolor);

    :deep(.van-tabs__wrap) {
      height: 59px;
    }

    :deep(.van-tabs__nav) {
      background: var(--ex-home-list-bgcolor);
    }

    :deep(.van-tab) {
      flex: none;
      font-size: 16px;
      margin-right: 30px;
      padding: 0;
      color: var(--ex-home-list-ftcolor) !important;
      background: var(--ex-home-list-bgcolor);
    }

    :deep(.van-tab--active) {
      font-weight: normal;
      color: var(--ex-home-list-ftcolor3) !important;
    }
  }
}
</style>
